<template>
    <div class="login-container">
        <el-form ref="login-form" :model="user" class="login-form" :rules="formrules">
            <el-form-item prop="phone">
                <el-input v-model="user.phone" placeholder="请输入手机号" ></el-input>
            </el-form-item>
             <el-form-item prop="code">
                <el-input v-model="user.code" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item prop="agree">
              <el-checkbox v-model="user.agree" class="login-checked">
                我已阅读并同意用户协议和隐私条款
              </el-checkbox>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onLogin" class="login-btn" :loading="loginLoading">登录1</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import {login} from '@/api/user'
export default {
  data () {
     return {
       user: {
         phone: '',
         code: '',
         agree:false
      },
      loginLoading:false,
        
        formrules:{
          phone:[
            {required:true,message:'请输入手机号码',trigger:'change'},
            {pattern:/^1[3,5,6,7,9,0]\d{9}$/,message:'请输入正确的手机号码格式',trigger:'change'}
          ],
          code:[
            {required:true,message:'请输入验证码',trigger:'change'},
            {pattern:/^\d{6}$/,message:'请输入正确的验证码格式'}
          ],
          agree:[
            {validator:(rule,value,callback)=>{
              if(value){
                callback()
              }else{
                callback(new Error('请勾选同意协议'))
              }
            }}
          ]
        }
    }
  },
  methods: {
    onLogin () {
     
      //表单验证
      this.$refs['login-form'].validate(valid=>{
        //如果表单验证失败  停止请求提交
        if(!valid){
          return 
        }
        //验证通过 请求登录
         this.login();
      });
      // this.loginLoading=true
      
    },
    login(){
      
      login(this.user).then(res=>{
        window.localStorage.setItem('user',JSON.stringify(res.data.data));
        console.info('登录成功');
        this.$message({
          message:'登录成功',
          type:'success'
        });
        
        this.$router.push('/');
        // this.loginLoading=false;
      }).catch(err=>{
        console.info('登录失败');
        this.$message.error('登录错误，手机或验证码错误');
        // this.loginLoading=false;
      });
      
    }
  }
}
</script>

<style lang="less" scoped>
 .login-container{
   position: fixed;
   left: 0;
   top: 0;
   right: 0;
   bottom: 0;
   display: flex;
   flex-direction: column;
   justify-content: center;
   align-items: center;
   background: url(./login_bg.jpg) no-repeat;
   background-size: cover;//覆盖  拉伸铺满
   .login-form{
     background-color: #fff;
     padding: 50px;
     min-width: 300px  ;
   }
  .login-btn{
    width: 100%;
  }
  
}
</style>
